<template>
  <div class="settlement-page">
    <!-- 操作按钮区域 -->
    <el-row :gutter="20" class="button-group">
      <el-col :span="1.5">
        <!-- 修改：添加导入上传组件 -->
        <el-upload
          class="upload-demo"
          action="#"
          :on-change="handleFileChange"
          :before-upload="beforeUpload"
          :auto-upload="false"
          :show-file-list="false"
        >
          <el-button>导入</el-button>
        </el-upload>
      </el-col>
      <el-col :span="1.5">
        <el-button @click="handleExport">导出</el-button>
      </el-col>
    </el-row>

    <!-- 查询条件区域 -->
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="结算状态">
        <el-select v-model="searchForm.settlementStatus" placeholder="请选择结算状态">
          <el-option label="未结算" value="未结算"></el-option>
          <el-option label="已结算" value="已结算"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建日期">
        <el-date-picker
          v-model="searchForm.createDate"
          type="daterange"
          range-separator="~"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-input v-model="searchForm.keyword" placeholder="请输入关键词搜索"></el-input>
      </el-form-item>

      <!-- 搜索和重置按钮 -->
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
      <br>

      <!--      新增和批量删除-->
      <el-form-item>
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="danger" :disabled="selectedIds.length === 0" @click="handleBatchDelete">
          批量删除
        </el-button>
      </el-form-item>
    </el-form>


    <!-- 表格区域 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
      v-loading="loading"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="statementNo" label="对账单号"></el-table-column>
      <el-table-column prop="carrier" label="承运商"></el-table-column>
      <el-table-column prop="settlementStatus" label="结算状态"></el-table-column>
      <el-table-column prop="totalOrders" label="订单总数量"></el-table-column>
      <el-table-column prop="goodsQuantity" label="货物数量"></el-table-column>
      <el-table-column prop="totalVolume" label="货物总体积"></el-table-column>
      <el-table-column prop="totalWeight" label="货物总重量"></el-table-column>
      <el-table-column prop="payableAmount" label="应付总金额(元)"></el-table-column>
      <el-table-column prop="actualAmount" label="实付总金额(元)"></el-table-column>
      <el-table-column prop="creator" label="创建人"></el-table-column>
      <el-table-column prop="createTime" label="创建时间"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="handleEdit(scope.row)">修改</el-button>
          <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px" @close="handleDialogClose">
      <el-form ref="editForm" :model="editForm" :rules="editFormRules" label-width="120px">
        <!-- 添加时隐藏ID字段，修改时显示 -->
        <el-form-item v-if="editForm.id" label="ID" prop="id">
          <el-input v-model="editForm.id" disabled/>
        </el-form-item>

        <el-form-item label="对账单号" prop="statementNo">
          <el-input v-model="editForm.statementNo" placeholder="请输入对账单号"/>
        </el-form-item>
        <el-form-item label="承运商" prop="carrier">
          <el-input v-model="editForm.carrier" placeholder="请输入承运商"/>
        </el-form-item>
        <el-form-item label="结算状态" prop="settlementStatus">
          <el-select v-model="editForm.settlementStatus" placeholder="请选择结算状态" style="width: 100%">
            <el-option label="未结算" value="未结算"></el-option>
            <el-option label="已结算" value="已结算"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单总数量" prop="totalOrders">
          <el-input-number
            v-model="editForm.totalOrders"
            :min="0"
            controls-position="right" style="width: 100%"
            placeholder="请输入订单总数量"
          />
        </el-form-item>
        <el-form-item label="货物数量" prop="goodsQuantity">
          <el-input-number
            v-model="editForm.goodsQuantity"
            :min="0"
            controls-position="right" style="width: 100%"
            placeholder="请输入货物数量"
          />
        </el-form-item>
        <el-form-item label="货物总体积" prop="totalVolume">
          <el-input-number
            v-model="editForm.totalVolume"
            :min="0"
            controls-position="right" style="width: 100%"
            placeholder="请输入货物总体积"
          />
        </el-form-item>
        <el-form-item label="货物总重量" prop="totalWeight">
          <el-input-number
            v-model="editForm.totalWeight"
            :min="0"
            controls-position="right" style="width: 100%"
            placeholder="请输入货物总重量"
          />
        </el-form-item>
        <el-form-item label="应付总金额" prop="payableAmount">
          <el-input-number
            v-model="editForm.payableAmount"
            :min="0"
            controls-position="right" style="width: 100%"
            placeholder="请输入应付总金额"
          />
        </el-form-item>
        <el-form-item label="实付总金额" prop="actualAmount">
          <el-input-number
            v-model="editForm.actualAmount"
            :min="0"
            controls-position="right" style="width: 100%"
            placeholder="请输入实付总金额"
          />
        </el-form-item>
        <el-form-item label="创建人" prop="creator">
          <el-input v-model="editForm.creator" placeholder="请输入创建人"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
      </div>
    </el-dialog>


    <!-- 分页区域 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="100"
    >
    </el-pagination>
  </div>
</template>

<script>
import {list, delAll, update, get, add, importData} from '@/api/tms/complete/all'
import * as XLSX from 'xlsx'
import FileSaver from 'file-saver'


export default {
  name: 'SettlementPage',
  data() {
    return {
      searchForm: {
        settlementStatus: '',
        createDate: [],
        keyword: ''
      },
      tableData: [], // 表格数据，这里设为空数组，即表格无数据
      loading: false,
      total: 0,
      dateRange: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      currentPage: 1,
      pageSize: 10,
      selectedIds: [], // 存储选中的行ID

      // 编辑相关数据
      dialogVisible: false,        // 编辑弹窗显示状态
      dialogTitle: '',             // 弹窗标题
      editForm: {                  // 编辑表单数据
        id: undefined,
        statementNo: '',
        carrier: '',
        settlementStatus: '',
        totalOrders: '',
        goodsQuantity: '',
        totalVolume: '',
        totalWeight: '',
        payableAmount: '',
        actualAmount: '',
        creator: ''
      },
      // 表单验证规则
      editFormRules: {
        statementNo: [{required: true, message: '请输入对账单号', trigger: 'blur'}],
        carrier: [{required: true, message: '请输入承运商', trigger: 'blur'}],
        settlementStatus: [{required: true, message: '请选择结算状态', trigger: 'change'}],
        totalOrders: [{required: true, message: '请输入订单总数量', trigger: 'blur'}],
        payableAmount: [{required: true, message: '请输入应付总金额', trigger: 'blur'}]
      },
      isAddMode: false // 标识是否为新增模式
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 添加：文件上传前校验
    beforeUpload(file) {
      const isExcel = file.name.endsWith('.xlsx') || file.name.endsWith('.xls')
      if (!isExcel) {
        this.$message.error('请上传Excel文件（.xlsx或.xls格式）')
        return false
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('文件大小不能超过2MB')
        return false
      }
      return true
    },
    // 添加：处理导入文件
    handleFileChange(file) {
      this.loading = true
      const reader = new FileReader()

      reader.onload = (e) => {
        try {
          // 读取Excel文件
          const data = new Uint8Array(e.target.result)
          const workbook = XLSX.read(data, {type: 'array'})

          // 获取第一个工作表
          const firstSheetName = workbook.SheetNames[0]
          const worksheet = workbook.Sheets[firstSheetName]

          // 将Excel数据转换为JSON
          const excelData = XLSX.utils.sheet_to_json(worksheet)

          if (excelData.length === 0) {
            this.$message.warning('Excel文件中没有数据')
            this.loading = false
            return
          }

          // 数据格式转换（根据实际Excel列名调整映射关系）
          const importData = excelData.map(item => ({
            statementNo: item['对账单号'] || '',
            carrier: item['承运商'] || '',
            settlementStatus: item['结算状态'] || '未结算',
            totalOrders: item['订单总数量'] || 0,
            goodsQuantity: item['货物数量'] || 0,
            totalVolume: item['货物总体积'] || 0,
            totalWeight: item['货物总重量'] || 0,
            payableAmount: item['应付总金额(元)'] || 0,
            actualAmount: item['实付总金额(元)'] || 0,
            creator: this.$store.state.user.name || 'system' // 假设从store获取当前用户
          }))

          // 这里可以添加数据验证逻辑

          // 调用后端导入接口（假设存在import接口）
          this.importData(importData)
        } catch (error) {
          console.error('Excel解析失败:', error)
          this.$message.error('Excel解析失败，请检查文件格式')
          this.loading = false
        }
      }

      reader.readAsArrayBuffer(file.raw)
    },
// 添加：导入数据到后端
    importData(data) {
      // 这里替换为实际的后端导入接口
      // 示例使用add接口批量导入，实际项目中可能需要专门的import接口
      Promise.all(data.map(item => add(item)))
        .then(() => {
          this.$message.success('导入成功')
          this.getList() // 重新加载数据
          this.loading = false
        })
        .catch(error => {
          console.error('导入失败:', error)
          this.$message.error('导入失败，请重试')
          this.loading = false
        })
    },

    // 添加：导出Excel方法
    handleExport() {
      if (!this.tableData || this.tableData.length === 0) {
        this.$message.warning('没有数据可导出')
        return
      }

      this.loading = true

      // 准备导出数据，将驼峰命名转换为中文标题
      const exportData = this.tableData.map(item => ({
        '对账单号': item.statementNo,
        '承运商': item.carrier,
        '结算状态': item.settlementStatus,
        '订单总数量': item.totalOrders,
        '货物数量': item.goodsQuantity,
        '货物总体积': item.totalVolume,
        '货物总重量': item.totalWeight,
        '应付总金额(元)': item.payableAmount,
        '实付总金额(元)': item.actualAmount,
        '创建人': item.creator,
        '创建时间': item.createTime
      }))

      // 创建工作簿和工作表
      const ws = XLSX.utils.json_to_sheet(exportData)
      const wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, ws, '结算数据')

      // 生成Excel文件并下载
      const excelBuffer = XLSX.write(wb, {bookType: 'xlsx', type: 'array'})
      const data = new Blob([excelBuffer], {type: 'application/octet-stream'})
      const fileName = `结算数据_${new Date().toLocaleDateString().replace(/\//g, '-')}.xlsx`

      FileSaver.saveAs(data, fileName)
      this.loading = false
      this.$message.success('导出成功')
    },
    /** 模糊搜索 */
    handleSearch() {
      this.getList()
      this.queryParams.pageNum = 1
    },

    /** 重置查询条件 */
    handleReset() {
      this.searchForm = {
        settlementStatus: '',
        createDate: [],
        keyword: ''
      }
      this.getList()
    },


    /** 查询列表数据 */
    getList() {
      this.loading = true
      const query = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        // settlementStatus: this.searchForm.settlementStatus,
        // keyword: this.searchForm.keyword
        // 可根据实际需求添加更多查询参数
      }

      // 添加结算状态查询条件
      if (this.searchForm.settlementStatus) {
        query.settlementStatus = this.searchForm.settlementStatus
      }

      // 添加关键词查询条件
      if (this.searchForm.keyword) {
        query.keyword = this.searchForm.keyword
      }

      // 日期范围处理
      if (this.searchForm.createDate && this.searchForm.createDate.length === 2) {
        // 开始日期保持不变
        const startDate = new Date(this.searchForm.createDate[0])
        const format = (date) => {
          const year = date.getFullYear()
          const month = String(date.getMonth() + 1).padStart(2, '0')
          const day = String(date.getDate()).padStart(2, '0')
          return `${year}-${month}-${day}`
        }

        query.beginTime = format(startDate)

        // 结束日期加一天，确保包含选择的那一天
        const endDate = new Date(this.searchForm.createDate[1])
        endDate.setDate(endDate.getDate() + 1)
        query.endTime = format(endDate)
      }

      console.log('发送查询参数:', query)

      list(query).then(response => {
        this.tableData = response.rows || response.data || []
        this.total = response.total || 0
        this.loading = false
      }).catch(error => {
        console.error('请求错误:', error)
        this.$message.error('获取数据失败')
        this.loading = false
      })
    },


    handleSizeChange(val) {
      this.pageSize = val
      this.queryParams.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.queryParams.pageNum = val
      this.getList()
    },
    // 处理选择变化
    handleSelectionChange(selection) {
      // 这里假设每行数据有id属性，实际项目中根据实际情况修改
      this.selectedIds = selection.map(item => item.id)
    },
    // 新增按钮点击事件
    handleAdd() {
      this.isAddMode = true
      this.dialogTitle = "新增对账单"
      // 重置表单数据
      this.editForm = {
        id: undefined,
        statementNo: '',
        carrier: '',
        settlementStatus: '',
        totalOrders: null,
        goodsQuantity: null,
        totalVolume: null,
        totalWeight: null,
        payableAmount: null,
        actualAmount: null,
        creator: ''
      }
      this.dialogVisible = true
    },


    // 修改按钮点击事件
    handleEdit(row) {
      this.isAddMode = false
      get(row.id).then(response => {
        const data = response.data || response

        console.log('获取到的数据:', data) // 调试用，查看数据结构

        // 修改这里的处理逻辑，将0值设置为null
        this.editForm = {
          id: data.id,
          statementNo: data.statement_no || '',
          carrier: data.carrier || '',
          settlementStatus: data.settlement_status || '',
          totalOrders: (data.total_orders !== undefined && data.total_orders !== 0) ? data.total_orders : null,
          goodsQuantity: (data.goods_quantity !== undefined && data.goods_quantity !== 0) ? data.goods_quantity : null,
          totalVolume: (data.total_volume !== undefined && data.total_volume !== 0) ? data.total_volume : null,
          totalWeight: (data.total_weight !== undefined && data.total_weight !== 0) ? data.total_weight : null,
          payableAmount: (data.payable_amount !== undefined && data.payable_amount !== 0) ? data.payable_amount : null,
          actualAmount: (data.actual_amount !== undefined && data.actual_amount !== 0) ? data.actual_amount : null,
          creator: data.creator || ''
        }

        this.dialogTitle = "修改对账单"
        this.dialogVisible = true
      }).catch(error => {
        this.$message.error('获取数据失败')
      })
    },

    // 提交编辑表单
    submitEditForm() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          if (this.isAddMode) {
            // 新增模式
            add(this.editForm).then(response => {
              this.$message.success('新增成功')
              this.dialogVisible = false
              this.getList() // 重新加载数据
            }).catch(error => {
              this.$message.error('新增失败')
            })
          } else {
            // 修改模式
            update(this.editForm).then(response => {
              this.$message.success('修改成功')
              this.dialogVisible = false
              this.getList() // 重新加载数据
            }).catch(error => {
              this.$message.error('修改失败')
            })
          }
        }
      })
    },

    // 关闭弹窗时的处理
    handleDialogClose() {
      this.$refs.editForm.resetFields()
      this.editForm = {
        id: undefined,
        statementNo: '',
        carrier: '',
        settlementStatus: '',
        totalOrders: '',
        goodsQuantity: '',
        totalVolume: '',
        totalWeight: '',
        payableAmount: '',
        actualAmount: '',
        creator: ''
      }
      this.isAddMode = false
    },

    handleDelete(row) {
      this.$confirm(`确定要删除ID为 ${row.id} 的记录吗？`, '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return delAll(row.id)
      }).then(() => {
        // 执行删除逻辑
        this.$message.success('删除成功')
        // 重新加载数据
        this.getList()
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
// 批量删除按钮点击事件
    handleBatchDelete() {
      if (this.selectedIds.length === 0) {
        this.$message.warning('请先选择要删除的记录')
        return
      }

      // 显示选中的ID列表
      let message = `确定要删除选中的 ${this.selectedIds.length} 条记录吗？`
      if (this.selectedIds.length <= 5) {
        message += `<br/>记录ID：${this.selectedIds.join(', ')}`
      } else {
        message += `<br/>记录ID：${this.selectedIds.slice(0, 5).join(', ')}...`
      }

      this.$confirm(message, '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        return delAll(this.selectedIds)
      }).then(() => {
        // 执行批量删除逻辑
        this.$message.success('删除成功')
        // 清空选择
        this.selectedIds = []
        // 重新加载数据
        this.getList()
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }
  }
}
</script>

<style scoped>
.settlement-page {
  padding: 20px;
}

.button-group {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 20px;
}
</style>
